<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/5/29
 * Time: 15:31
 * Mail:87658989@qq.com
 */

namespace app\adminapi\model;

use app\adminapi\filter;
use app\base\exception\BaseException;
use app\base\exception\RecordNotFoundException;
use think\exception\DbException;
use traits\model\SoftDelete;

class Company extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function companyList($fields='*',$where=[],$page=1,$num=10){
        $filter          = new filter\CompanyList();
        $filter->analyzeField();
        list(,$msg)      = $filter->checkField($fields);
        list(,$whereMsg) = $filter->checkWhere($where);
        $data['note'] = "查询条件json输入格式如{'passenger_id':['in','6,7,8,9,10,11,12'],'passenger_name':['like','%王%']}";

        $buildQuery = function($query) use ($whereMsg) {
            self::authCompanyQuery($query, $whereMsg, 'a.company_id');
        };

        try{
            $data['data'] = $this->alias('a')
                ->field($msg)
                ->where($buildQuery)
                ->page($page,$num)
                ->order('a.company_id desc')
                ->select();
        }catch (DbException $e){
            abort(0,$e->getMessage());
        }
        $data['count'] = $this->alias('a')
            ->where($buildQuery)
            ->order('a.company_id desc')
            ->count();
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }


    /**
     * 新增或编辑单位
     * @param $params
     * @return $this|false|int
     * @throws BaseException
     * @throws DbException
     * @throws RecordNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createOrUpdate($params) {
        $user = new User();
        $session = $user->getLoginUser();

        // 超级管理员才能添加
        if(!isset($params['company_id'])) {
            $this->checkAdminAuth($session, self::AUTH_SCOPE_SUPER_ADMIN);
        }else{
            $this->checkAdminAuth($session, self::AUTH_SCOPE_EITHER);
        }

        if(isset($params['company_id'])) {
            $where = ['company_id' => $params['company_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'company_id', null, true);
            };
            $record = self::get($buildQuery);
            if(!$record) {
                throw new RecordNotFoundException();
            }
        }elseif (!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 添加或者编辑了单位名称时，检验单位名称是否重复
        if(!isset($params['company_id']) || ( isset($record) && $record && $record->getAttr('company_name') !== $params['company_name'])){
            $checkName = $this->where('company_name', $params['company_name'])->find();
            if($checkName){
                throw new BaseException('该单位名称已存在');
            }
        }

        // 添加或者编辑了用户id时，检验用户id是否重复
        if(!isset($params['company_id']) || ( isset($record) && $record && $record->getAttr('user_id') != $params['user_id'])){
            $checkUser = $this->where('user_id', $params['user_id'])->find();
            if($checkUser){
                throw new BaseException('其他单位已绑定该用户，不能重复绑定');
            }
        }

        // 验证用户是否存在
        $user = $this->addRelativeFields( $params, 'app\adminapi\model\User', $params['user_id'],  [], '绑定账号不存在');

        // 选中的用户不属于任何公司时，绑定到该公司
        $u_company_id = $user->getAttr('company_id');
        if(!$u_company_id){
            $user->company_id = $params['company_id'];
            $user->save();
        }elseif($u_company_id !== intval($params['company_id'])){
            throw new BaseException('该用户已绑定其他单位，不能重复绑定');
        }

        if(isset($params['company_id'])) {

            return $this->isUpdate(true)->save($params);
        }

        $this->data($params)->save();
        return $this;
    }
}